/*
 *
 *  Copyright (C) 2010 GSyC/LibreSoft, Universidad Rey Juan Carlos.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see http://www.gnu.org/licenses/. 
 *
 *  Author : Raúl Román López <rroman@gsyc.es>
 *
 */

package com.LibreGeoSocial.App.OMF;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;

import android.util.Log;

public class SMSSender {
	
	// URL del servidor https que recibe la petici�n
	private static final String url = "https://opensms.movistar.es/aplicacionpost/loginEnvio.jsp";
	private static TrustManager[] trustManagers;
	
	public String SendMessage (String Login,String Pwd, String Dest, String Msg){
		
		//C�digo de respuesta servidor a la petici�n https
		String httpResponse = "";
		
		try {
			SMSSender.allowAllSSL();
			// URL de la petici�n
			URL url = new URL(SMSSender.url);   
			   
	        // Establece la conexi�n   
			HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
			
			
			connection.setDoOutput(true);
	        // Establece las cabeceras de la petici�n http

	        connection.setRequestMethod("POST");
			connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");       
			connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322; Media Center PC 4.0; .NET CLR 2.0.50727)"); 
			connection.setRequestProperty("Accept", "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*"); 
			connection.setRequestProperty("Connection", "Keep-Alive");
			 
			// Datos asociados a la petici�n
			String data = "TM_ACTION=AUTHENTICATE";
	        data +="&TM_LOGIN=" + Login;
	        data += "&TM_PASSWORD=" + Pwd;
	        data += "&to=" + Dest;
	        data += "&message=" + Msg;
			
	        // Envia los datos asociados a la petici�n   

	        OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());   
	        wr.write(data);
	        wr.flush();   
	        	        
	        if (connection.getResponseCode() == HttpsURLConnection.HTTP_OK){   
	            // Lee el contenido de la respuesta y lo retorna   
	            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));   
	            String         line   = reader.readLine();   
	            while (line != null) {   
	                httpResponse = line.toString();
	                line = reader.readLine();     
	            }   
	            reader.close();   
	        } else {   
	           httpResponse = connection.getResponseMessage();
	        }   
	         
	        
	        // Cierra la conexi�n   
	        connection.disconnect();   

		} catch (MalformedURLException me) {
	        httpResponse = me.toString();
		} catch (IOException ioe) {
			 httpResponse = ioe.toString();
		} catch (Exception e) {
			 httpResponse = e.toString();
		}
		
		// Retorna el contenido de la respuesta
		return httpResponse;
	}
	
	public static void allowAllSSL(){
		javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier(){

			public boolean verify(String hostname, SSLSession session) {
				// TODO Auto-generated method stub
				return true;
			}
			
		});
		
		javax.net.ssl.SSLContext context = null;
		
		if(trustManagers==null){
			trustManagers = new javax.net.ssl.TrustManager[]{new _FakeX509TrustManager()};
		}
		
		try{
			context = javax.net.ssl.SSLContext.getInstance("TLS");
			context.init(null, trustManagers, new SecureRandom());
			
		}catch(NoSuchAlgorithmException e){
			Log.e("allowAllSSL", e.toString());
		}catch(KeyManagementException e){
			Log.e("allowAllSSL", e.toString());
		}
		
		javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
		
	}
	
	public static class _FakeX509TrustManager implements javax.net.ssl.X509TrustManager{
		
		private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[]{};
		
		public void checkClientTrusted(X509Certificate[] chain, String authType)
				throws CertificateException {
			// TODO Auto-generated method stub
			
		}

		public void checkServerTrusted(X509Certificate[] chain, String authType)
				throws CertificateException {
			// TODO Auto-generated method stub
			
		}
		
		public boolean isClientTrusted(X509Certificate[] chain){
			return true;
		}
		
		public boolean isServerTrusted(X509Certificate[] chain){
			return true;
		}
		
		public X509Certificate[] getAcceptedIssuers() {
			// TODO Auto-generated method stub
			return _AcceptedIssuers;
		}
		
	}
	
	
	
}